package com.morehair.service.admin.impl;

import com.github.pagehelper.PageInfo;
import com.morehair.bean.bo.admin.BaseReq;
import com.morehair.bean.bo.admin.TopicReq;
import com.morehair.bean.pojo.Topic;
import com.morehair.bean.pojo.TopicExample;
import com.morehair.bean.vo.admin.BaseData;
import com.morehair.mapper.TopicMapper;
import com.morehair.service.admin.TopicService;
import com.morehair.utils.AdPageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Author: DLX
 * @Date: 2021/6/6 20:39
 * @Description:
 **/
@Service
@Transactional
public class TopicServiceImpl implements TopicService {

    @Autowired
    TopicMapper topicMapper;

    @Override
    public BaseData<Topic> query(BaseReq baseReq) {
        AdPageHelper.startPage(baseReq);

        TopicReq topicReq = (TopicReq) baseReq;
        String title = topicReq.getTitle();
        String subtitle = topicReq.getSubtitle();

        TopicExample topicExample = new TopicExample();
        TopicExample.Criteria criteria = topicExample.createCriteria();

        criteria.andDeletedEqualTo(false);
        if (title != null && !"".equals(title)) {
            criteria.andTitleLike("%" + title + "%");
        }
        if (subtitle != null && !"".equals(subtitle)) {
            criteria.andSubtitleLike("%" + subtitle + "%");
        }

        List<Topic> topics = topicMapper.selectByExample(topicExample);
        PageInfo<Topic> topicPageInfo = new PageInfo<>(topics);
        long total = topicPageInfo.getTotal();

        return BaseData.ok(topics, total);

    }

    @Override
    public Topic topicCreate(Topic topic) {
        Date date = new Date();
//        Date addTime = date;
//        Date updateTime = date;
        topic.setAddTime(date);
        topic.setUpdateTime(date);
        topicMapper.insertSelective(topic);
        Topic newTopic = topicMapper.selectNewTopic();
        return newTopic;
    }

    @Override
    public Topic topicUpdate(Topic topic) {
        Date updateTime = new Date();
        topic.setUpdateTime(updateTime);
        int i = topicMapper.updateByPrimaryKeySelective(topic);
        if (i == 1) {
            return topicMapper.selectByPrimaryKey(topic.getId());
        }
        return null;
    }

    @Override
    public int topicDelete(Topic topic) {
        topic.setDeleted(true);
        int affectedRows = topicMapper.updateByPrimaryKeySelective(topic);
        if (affectedRows == 1) {
            return 200;
        }
        return 404;
    }
}
